package win.zxshuo.www.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.net.URLEncoder;
import java.util.Map;

public class JuheSMSUtils {

    /**
     * 聚合数据发送短信的工具类。
     */

    public static final String REQUEST_URL="http://v.juhe.cn/sms/send";

    /**
     * 聚合数据API 发送短信方法
     * @param mobile
     * @param templateId
     * @param tpl_value
     * @param key
     * @throws Exception
     */
    public static void sendSMS(String mobile,String templateId,String tpl_value,String key) throws Exception{
        String url = REQUEST_URL+"?mobile="+mobile+"&tpl_id="+templateId+"&tpl_value="+tpl_value+"&key="+key;
        CHttpClient cHttpClient = new CHttpClient();
        String result = cHttpClient.get(url);
        JSONObject jsonObject = JSON.parseObject(result);
        if (!jsonObject.getString("reason").equals("短信发送成功")&& !jsonObject.getString("reason").equals("操作成功")&&!jsonObject.getString("error_code").equals(0)){
            throw new Exception("短信发送失败，详情："+result);
        }
    }


    /**
     * 将变量组织为template_value
     * @param params
     * @return
     * @throws Exception
     */
    public static String makeTplValue(Map<String,String> params) throws Exception{
        String paramsStr= "";
        for (Map.Entry<String,String> entry:params.entrySet()){
            String tmpStr = "";
            if (entry.getKey().contains("#")||entry.getKey().contains("&")||entry.getKey().contains("=")){
                tmpStr += URLEncoder.encode(entry.getKey(),"UTF-8");
            }else {
                tmpStr += "#"+entry.getKey()+"#=";
            }
            if (entry.getValue().contains("#")||entry.getValue().contains("&")||entry.getValue().contains("=")){
                tmpStr += URLEncoder.encode(entry.getValue(),"UTF-8");
            }else {
                tmpStr += entry.getValue();
            }
            paramsStr += URLEncoder.encode(tmpStr+"&","UTF-8");
        }
        return paramsStr.toLowerCase();
    }


}
